<template>
  <div class="databackup">
    <!--数据备份 dataBackup-->
    <div class="con">
         <div class="lefttree">
              <div class="daorubtn active" @click="importExportfn('导入')">工程导入</div>
              <div class="daorubtn" @click="importExportfn('导出')">工程导出</div>
         </div>
         <input  type="file" ref="dianfileInput" accept=".db"   @change="handleFileChange"  style="display: none">
         <div class="rightcon">
            <div class="mytitle">
                <span></span>数据列表
            </div>
            <div class="mytable">
              <el-table :data="tableData" height="100%" stripe  style="width: 100%;" >
                          <el-table-column type="index" width="120" label="序号"> </el-table-column>
                          <el-table-column prop="device_name"  label="名称"> </el-table-column>
                          <el-table-column prop="device_address" label="修改日期"> </el-table-column>   
                          <el-table-column prop="device_address" label="类型"> </el-table-column>   
                          <el-table-column prop="device_address" label="大小" width="240"> </el-table-column>   
               </el-table>
            </div>
         </div>
         <!-- 新增/修改 设备-->
          <el-dialog width="1000px" draggable  :title="nowOperatingDevice" :close-on-click-modal='false' v-model="importExport">
                    <div class="juticon">
                         <div class="toptype">
                             <div class="mytype">
                                <div style="font-size:14px">导入数据类型：</div>
                                <el-checkbox v-model="mychange">通道设备</el-checkbox>
                                <el-checkbox v-model="mychange">设备模板</el-checkbox>
                                <el-checkbox v-model="mychange">协议转发</el-checkbox>
                                <el-checkbox v-model="mychange">转发类型</el-checkbox>
                             </div>
                             <div class="daorubtns">
                                <el-button  class="last-el-button" type="primary"><img src="../../assets/btnImg/2.0.png" alt="" style="margin-right:6px">{{nowOperatingDevice}}</el-button>
                             </div>
                         </div>
                         <div class="filetree">
                              <el-scrollbar style="height:calc(100% - 10px);width: 99%;">
                                  <el-tree class="filter-tree" :data="daorudataList"  
                                      :expand-on-click-node="true" 
                                      default-expand-all
                                      show-checkbox
                                      :props="defaultProps" :highlight-current='true'  ref="treedaoru" 
                                  >
                                      <template #default="{ node }">
                                                      <div class="custom-tree-node" >
                                                              <div style="display: flex;align-items: center;">
                                                                  <img src="../../assets/btnImg/2.0.png" alt="">
                                                                  <span style="font-size:14px;color:#1a1a1a;margin-left:4px"> {{ node.label }}</span>
                                                              </div>
                                                      </div>
                                      </template>
                                  </el-tree>
                              </el-scrollbar>
                         </div>
                         
                    </div>
                    <div class="el-loading-mask" v-show="diaisMask">
                                    <div class="el-loading-spinner">
                                    <svg viewBox="25 25 50 50" class="circular">
                                        <circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
                                    </svg>
                           </div>
                     </div>
                   <template #footer >
                      <div class="dialog-footer">
                            <el-button  class="last-el-button" @click="saveDevicefn" type="primary">完成</el-button>
                      </div>
                    </template>
                      
                    
          </el-dialog>
          <el-dialog width="500px" draggable  title="导入提示"   v-model="daorudiofalse" :close-on-click-modal='false' :show-close='false'>
                    <div class="choicedio">
                         <div class="infoitems" style="font-size:16px">
                            工程上传成功，需要重启网关生效，确定要重启网关吗？
                         </div>
                    </div>
                      <template #footer>
                            <div class="dialog-footer">
                                 <el-button  @click="daorudiofalse = false">取 消</el-button>
                                 <el-button  class="last-el-button"  type="primary" @click="fugaifn">确 定</el-button>
                            </div>
                    </template> 
         </el-dialog>
         <div class="el-loading-mask" v-show="isMask">
             <div class="el-loading-spinner"><svg viewBox="25 25 50 50" class="circular"> <circle cx="50" cy="50" r="20" fill="none" class="path"></circle></svg></div>
          </div>
    </div>
  </div>
</template>

<script>
import {restartSystem,pingSystem} from "../../api/forwardApi";
import {ProjectImport,ProjectExport} from "../../api/Interface";

export default {


  data() {
    return {
       isMask:false,
       daorudiofalse:false,
       tableData:[],
       importExport:false,
       nowOperatingDevice:"导入",
       diaisMask:false,
       mychange:true,
       daorudataList:[
         {
           name:"管理机工具",
           children:[]
         }
       ],
       defaultProps: {
                children: 'children',
                label: 'name',
        },
    };
  },

  mounted() {
    
  },

  methods: {
     /**
 * 下载后端返回的 SQLite .db 文件
 * @param {string} url - 后端接口地址
 * @param {string} filename - 下载的文件名（如 'database.db'）
 */
async  downloadDbFile(url) {
  try {
    // 1. 发起请求，获取二进制数据
    const response = await fetch(url,{
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json', // 根据后端要求调整
      },
    });
    
    if (!response.ok) {
      throw new Error(`请求失败: HTTP ${response.status}`);
    }
    // console.log("导出",response);

    // 2. 获取 Blob 数据（MIME 类型为 application/x-sqlite3）
    const blob = await response.blob();

    // 3. 创建临时下载链接
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = 'webserver.db'; // 设置文件名
    document.body.appendChild(link);

    // 4. 触发下载
    link.click();
    this.isMask = false

    // 5. 清理临时对象
    setTimeout(() => {
      window.URL.revokeObjectURL(downloadUrl);
      document.body.removeChild(link);
    }, 100);
  } catch (error) {
    this.$message.error('导出工程失败')
    // console.error('下载失败:', error);
    // alert('文件下载失败，请重试或联系管理员');
  }
},


    importExportfn(type){
      //  this.nowOperatingDevice = type
      //  this.importExport = true
      if(type == '导入'){
         this.$refs.dianfileInput.click();
      }else {
        this.isMask = true
        this.downloadDbFile('/Project/Export');
        return
         ProjectExport().then(res => {
             console.log("导出",res);
            this.isMask = false
            if(res != undefined){
                const content = res;
                // this.exportAsSQL(content)
                // const blob = new Blob([content], { type: 'text/plain' });
                // const url = URL.createObjectURL(blob);
                
                // const a = document.createElement('a');
                // a.href = url;
                // a.download = 'webserver.db'; // 设置文件名
                // a.click();
                
                // URL.revokeObjectURL(url); // 释放内存
            }else {
               this.$message.error('导出工程失败')
            }
         })
      }
    },
    handleFileChange(event){
      const files = event.target.files;
      let formData = new FormData()
      formData.append('file', files[0]);
        this.isMask = true
      ProjectImport(formData).then(res => {
        //  console.log("导入工程",res);
          if(res != undefined){
            this.isMask = false
            this.daorudiofalse = true
          }else {
            this.isMask = false
            this.$message.error('导入工程失败')
          }
      })
      
    },
    fugaifn(){
        this.daorudiofalse = false
        this.isMask = true
        //  融合版为1，纯净版为2
        restartSystem({'model':2}).then(res => {})
				setTimeout(() => {
					this.viewChongqi()
				},10000)
    },
    //检查管理机是否重启完成
	 viewChongqi(){
      pingSystem().then(res => {
        // console.log("检查管理机心跳",res);
        if(res.code == 200){
          this.isMask = false
          this.$message({showClose: true,message: '重启成功',type: 'success'});
        }else {
          setTimeout(() => {
            this.viewChongqi()
          },2000)
        }
      }).catch(() => {
        setTimeout(() => {
          this.viewChongqi()
        },2000)
      })
	 },
    saveDevicefn(){

    },
  },
};
</script>
<style lang="scss" scoped>
    .databackup {
          width: 100%;
          height: 100%;
          :deep(.el-icon svg){
             top: 3px;
          }
          .con {
             width: 100%;
             height: 100%;
             display: flex;
             position: relative;
             .lefttree {
               width: 230px;
               height: 100%;
               background-color: #fff;
               margin-right: 8px;
               padding: 12px;
               box-sizing: border-box;
               .daorubtn {
                 width: 100%;
                 height: 67px;
                 border: 1px solid #D8D8D8;
                 box-sizing: border-box;
                 border-radius: 4px;
                 overflow: hidden;
                 font-size: 24px;
                 display: flex;
                 align-items: center;
                 justify-content: center;
                 color:#1A1A1A;
                 margin-bottom: 12px;
                 &.active {
                   background-color: #3C89F2;
                   border-color: #3C89F2;
                   color: #fff;
                 }
               }
             }
             .rightcon {
               width: calc(100% - 238px);
               height: 100%;
               background-color: #fff;
               padding: 12px;
               box-sizing: border-box;
               .mytitle {
                 width: 100%;
                 height: 36px;
                 background-color: #F0F5FF;
                 border-radius: 4px;
                 display: flex;
                 align-items: center;
                 color: #000;
                 font-size: 15px;
                 span {
                     display: inline-block;
                     width: 3px;
                     height: 18px;
                     background-color: #2178F1;
                     margin-left: 12px;
                     margin-right: 6px;
                     border-radius: 3px;
                 }
               }
               .mytable {
                 width: 100%;
                 height: calc(100% - 50px);
                 margin-top: 12px;
               }
             }
          }
          .juticon {
             width: 100%;
             height: 550px;
             padding: 12px;
             box-sizing: border-box;
             .toptype {
              width: 100%;
               display: flex;
               align-items: center;
               justify-content: space-between;
               .mytype {
                 display: flex;
                 align-items: center;
               }
             }
             .filetree {
               width: 100%;
               height: calc(100% - 68px);
               margin-top: 20px;
             }
          }
    }
</style>